package cn.z2huo.demo.spring.transactional.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

@Configuration
public class MyTransactionManager implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static PlatformTransactionManager getManager() {
        return applicationContext.getBean(PlatformTransactionManager.class);
    }

    public static TransactionStatus start() {
        TransactionStatus transactionStatus = getManager().getTransaction(TransactionDefinition.withDefaults());
        return transactionStatus;
    }

    public static void commit(TransactionStatus transaction) {
        getManager().commit(transaction);
    }

    public static void rollback(TransactionStatus transaction) {
        getManager().rollback(transaction);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MyTransactionManager.applicationContext = applicationContext;
    }
}
